import { baseRoutes, editRoutes, detailRoutes } from '@/routes';
import { BaseLayout, EditLayout, DetailLayout } from '@/components/Layout';
import { QueryClient, QueryClientProvider } from 'react-query';
import { Switch, Route, Redirect } from 'react-router-dom';

import GlobalVarContext from '@/context';
import { useEffect } from 'react';
import { useGroup, useInitData } from '@/hooks';

const queryClient = new QueryClient({
   defaultOptions: {
      queries: {
         refetchOnWindowFocus: false,
         retry: false,
      },
   },
});

/**
 * DataProvider： 获取全局状态，注入到各个页面，使用的上下文
 * ========================================================
 * 对于上下文，推荐放入有以下特点的内容
 *    1. 对大部分页面有影响
 *    2. 不会频繁更新
 * 比如 分类、用户、当前组织
 */
const DataProvider = ({ children }) => {
   const {
      user,
      categories,
      refetchUser,
      isNoticeNew,
      refetchNoticeStatus,
      isLoading,
   } = useInitData();

   // 懒更新，挂载后不会自动请求，只有当groupId变化时重新获取
   const { data: group, refetch: refetchGroup } = useGroup(user.mainGroup);
   useEffect(() => {
      if (user.mainGroup !== '') {
         refetchGroup();
      }
   }, [user.mainGroup]);

   if (isLoading) {
      return <div>Loading...</div>;
   }

   return (
      <GlobalVarContext.Provider
         value={{
            groupId: user.mainGroup,
            categories,
            group,
            refetchGroup,
            user,
            refetchUser,
            isNoticeNew,
            refetchNoticeStatus,
         }}
      >
         {children}
      </GlobalVarContext.Provider>
   );
};

export default function Main() {
   return (
      <QueryClientProvider client={queryClient}>
         <DataProvider>
            <Switch>
               <Route exact path="/" key="redirect">
                  <Redirect to="/home" />
               </Route>
               {/* 编辑类 */}
               {editRoutes.map((item) => (
                  <Route exact path={item.path} key={item.key}>
                     <EditLayout title={item.title}>
                        {item.component}
                     </EditLayout>
                  </Route>
               ))}
               {baseRoutes.map((item) => (
                  <Route exact path={item.path} key={item.key}>
                     <BaseLayout>{item.component}</BaseLayout>
                  </Route>
               ))}

               {/* 详情类 */}
               {detailRoutes.map((item) => (
                  <Route exact path={item.path} key={item.key}>
                     <DetailLayout>{item.component}</DetailLayout>
                  </Route>
               ))}
               <Route path="*" key="not-found">
                  <div>no</div>
               </Route>
            </Switch>
         </DataProvider>
      </QueryClientProvider>
   );
}
